package com.sprint.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sprint.controller.utils.R;
import com.sprint.domain.Book;
import com.sprint.service.IBookService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@ResponseBody
@RequestMapping("/books")
public class BookController2 {

    @Autowired
    private IBookService bookService;

    @GetMapping
    public R getAll()
    {
        return new R(true,bookService.list());
    }

    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id)
    {
        return new R(true,bookService.getById(id));
    }


    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        /*R r = new R();
        r.setFlag(true);*/
        if(book.getName().equals("123")) throw new IOException();
        boolean flag = bookService.save(book);
        return new R(flag, flag ? "加载成功":"加载失败"); // 三元运算 作为判断
    }

    @PutMapping
    public R updatebyId(@RequestBody Book book)
    {
        return new R(bookService.updateById(book));
     }

    @DeleteMapping("{id}")
    public R deletebyId(@PathVariable Integer id)
    {
        return new R(bookService.removeById(id));
    }

    /*@GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize)
    {
        //如果当前页码值大于最大页码值，重新查询
        IPage<Book> page2 = bookService.getPage2(currentPage, pageSize);
        if(currentPage>page2.getPages())
        {
            page2  = bookService.getPage2((int) page2.getPages(), pageSize);
        }
        return new R(true, page2);
    }*/

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize,String name, Book book)
    {
        System.out.println("Name => " + name);
        LambdaQueryWrapper<Book> lambdaQueryWrapper = new LambdaQueryWrapper<Book>();
        //lambdaQueryWrapper.like(Strings.isNotEmpty(book.getType()),book :: getType());
        //如果当前页码值大于最大页码值，重新查询
        IPage<Book> page2 = bookService.getPage2(currentPage, pageSize);
        if(currentPage>page2.getPages())
        {
            page2  = bookService.getPage2((int) page2.getPages(), pageSize);
        }
        return new R(true, page2);
    }

}

